<?php

/**
 * @file IndexController
 * @author garypradoruiz <garypradoruiz@gmail.com>
 * @link mailto:garypradoruiz@gmail.com
 * @copyleft 2012 garypradoruiz
 * @license GPL
 * @version 1
 */
class Orden_OrdenController extends Zend_Controller_Action {
    /*
     * status orden
     */

    protected $_PENDING = 0;
    protected $_PROGRESS = 1;
    protected $_REVIEWING = 2;
    protected $_REVISED = 3;
    protected $_DENY = 4;
    protected $_COMPLET = 5;
    protected $_SEND_EMAIL_NEW_ORDER = 0;
    protected $_SEND_EMAIL_CHANGE_ORDER = 1;
    protected $_SEND_EMAIL_DENY_ORDER = 2;

    public function init() {
        /* Initialize action controller here */
    }

    /*
     * Function that only show orders client logued
     */

    public function indexAction() {
        $ordenDb = new Orden_Model_DbTable_Orden();

        $select = $ordenDb->select()->setIntegrityCheck(false)
                ->from(array('o' => 'orden'), array('code', 'title', 'create_date', 'end_date', 'status'))
                ->join(array('ou' => 'orden_user'), 'o.id = ou.id_orden')
                ->join(array('u' => 'user'), 'u.id = ou.id_user')
                ->join(array('cl' => 'client'), 'cl.id = u.client_departament');

        $dataOr = $ordenDb->fetchAll($select);
        $this->view->ordenes = $dataOr;
    }

    /*
     * Orden edited and status admin of agency 
     */

    public function editOrdenAction() {
        $ordenDb = new Orden_Model_DbTable_Orden();
        $id_orden = $this->_request->getParam('id', 0);

        $auth = Zend_Auth::getInstance();
        $iduser = $auth->getIdentity()->id;

        if ($this->getRequest()->isPost()) {
            $data = $this->_request->getParams();

            if ($data['radio_status'] == $this->_PROGRESS) {
                $descriptionDeny = $data['deny_description'];
                $where = $ordenDb->getAdapter()->quoteInto('id=?', $id_orden);
                $newData = array(
                    'status' => $this->_PROGRESS,
                    'deny_description' => $descriptionDeny
                );
                $ordenDb->update($newData, $where);
                $msg = 'Orden Aceptada. Un mensaje de confirmaci&oacute;n ha sido enviado a su correo y una copia a los encargados de agencia. 
                        Codigo de Orden: ' . 'XAVR' . $id_orden;
                $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                $sendEmail->sendEmail($id_orden, 'ORDEN_ACCEPT'); // Enviar email si la orden fue aceptada
            } else {  // Deny Orden and send email to client
                if ($data['radio_status'] == $this->_DENY) {
                    $descriptionDeny = $data['deny_description'];
                    $where = $ordenDb->getAdapter()->quoteInto('id=?', $id_orden);
                    $newData = array(
                        'status' => $this->_DENY,
                        'deny_description' => $descriptionDeny
                    );
                    $ordenDb->update($newData, $where);
                    $msg = 'Orden Rechazada. Un mensaje de confirmaci&oacute;n ha sido enviado a su correo y una copia a los encargados de agencia. 
                            Codigo de Orden: ' . 'XAVR' . $id_orden;
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($id_orden, 'ORDEN_DENY'); // Enviar email si la orden fue denegada
                }
            }
            $this->_helper->FlashMessenger()
                    ->setNamespace('success')
                    ->addMessage($msg);
            $this->_helper->redirector->gotoUrlAndExit('/orden/orden/index');
        } else {
            $id = $this->_request->getParam('id', 0);
            $ordenDb = new Orden_Model_DbTable_Orden();
            $select = $ordenDb->select()->where('id=?', $id)->where('deleted=?', '0');
            $result = $ordenDb->fetchRow($select);
            $this->view->orden = $result;
        }
    }

    /*
     * Detail of orden only ordenes of a user client
     * also change status and add comment to orden
     */

    public function viewDetailOrdenAction() {
        $id = $this->_request->getParam('id', 0);
        $ordenDb = new Orden_Model_DbTable_Orden();
        $messageDb = new Orden_Model_DbTable_OrdenMessage();
        $auth = Zend_Auth::getInstance();
        $iduser = $auth->getIdentity()->id;

        if ($this->_request->isPost()) {
            $data = $this->_request->getParams();
            $ordenDb->update(array('status' => $data['status']), 'id=' . $data['id_orden']);
            $messageDb->insert(array('message' => $data['message'], 'id_orden' => $data['id_orden'], 'id_user' => $iduser));
            // enviar email con el cambio de estado
            $descriptionDeny = $data['deny_description'];
            $where = $ordenDb->getAdapter()->quoteInto('id=?', $id);
            $newData = array(
                'status' => $this->_DENY,
                'deny_description' => $descriptionDeny
            );
            $ordenDb->update($newData, $where);
            switch ($data['status']) {
                case 2:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($id, 'ORDEN_ATHOS_REVIEW'); /// cliente revisando
                    break;
                case 3:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($id, 'ORDEN_ATHOS_REVISED'); /// cliente ha revisado
                    break;
                case 4:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($id, 'ORDEN_ATHOS_COMPLETE'); /// cliente ha completado
                    break;
            }
            $this->_helper->FlashMessenger()
                    ->setNamespace('success')
                    ->addMessage('Usted realizo el cambio de estado en la orden XAVR' . $data['id_orden'] . ', se notificara a los involucrados para proceder.');
            $this->_redirect('/orden/orden/index');
        } else {
            $result = $ordenDb->fetchRow('id=' . $id);

            $selectMessage = $messageDb->select()->setIntegrityCheck(false)
                    ->from(array('om' => 'orden_message'), array('id_orden', 'message', 'create_date', 'id_orden'))->where('om.id_orden=?', $id)
                    ->join(array('u' => 'user'), 'u.id = om.id_user');
            $resultMessage = $messageDb->fetchAll($selectMessage);
            $this->view->details = $result;
            $this->view->messages = $resultMessage;
        }
    }

}

?>